package com.oj.auth.entity;

import com.oj.api.auth.domain.AccountInfo;
import com.oj.api.auth.domain.UserGroupInfo;
import com.oj.common.data.BaseEntity;
import com.oj.common.data.ICommonRepository;
import com.oj.common.util.BeanUtil;
import com.oj.common.util.ContextUtil;
import lombok.*;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 系统用户组实体
 * Created by Bing on 2018/5/11.
 */
    @Entity(name = "AUTH_USER_GROUPS")
@Table(indexes = {
        @Index(name = "auth_idx_code_user_groups", unique = true,columnList = "code")
})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class UserGroupEntity extends BaseEntity<UserGroupInfo> {

    /**
     * 描述
     * 验证码
     */
    private String remark,checkCode;

    /**
     * 题目集codes
     */
    @Column(length = 2000)
    /**
     * 邀请码
     */
    private String problemSetCodes;
    @Column(length = 2000)
    private String pinCodes;


    /**
     * 用户列表
     */
    @ManyToMany(cascade = CascadeType.REFRESH,fetch = FetchType.LAZY)
    @JoinTable(name="CORE_UGE_AE",joinColumns = @JoinColumn(name="UGE_ID",referencedColumnName = "PK_ID"),
                inverseJoinColumns = @JoinColumn(name = "AE_ID",referencedColumnName = "PK_ID"))
    @OrderBy(value = "code")
    private Set<AccountEntity> users;


    @Override
    protected UserGroupInfo createInfo() {
        return new UserGroupInfo();
    }

    @Override
    public UserGroupInfo buildInfo(UserGroupInfo userGroupInfo) {
        super.buildInfo(userGroupInfo);
        List<AccountInfo> list = new ArrayList<>();
        this.users.forEach(a->{
            AccountInfo info = new AccountInfo();
            BeanUtil.beanCopy(a, info);
            list.add(info);
        });
        userGroupInfo.setUsers(list);
        return userGroupInfo;
    }

    public void addUser(AccountEntity accountEntity){
        if(this.users==null){
            this.users = new HashSet<>();
        }
        this.users.add(accountEntity);
    }
}
